package com.xxl.job.admin.controller.interceptor;

import com.xxl.job.admin.controller.UserController;
import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Zhihj
 * @Date: 2023-10-12 21:39:59
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);
    @Autowired
    private LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            //如果拦截的不是方法  则跳过进入下一个拦截器
            return true;
        }
        Boolean needLogin = true;
        Boolean needAdminuser = false;
        HandlerMethod method = (HandlerMethod) handler;
        PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class);
        if(permission != null){
            //获取到注解的参数
            needLogin = permission.limit();
            needAdminuser = permission.adminuser();
        }
        logger.info("needLogin的值为："+needLogin);
        logger.info("needAdminuser的值为："+needAdminuser);
        if(needLogin){//需要登录
            //调用方法查看是否登录 具体方法还没写
            XxlJobUser loginUser = loginService.ifLogin(request,response);
            if(loginUser == null){
                //没有登陆，不允许访问该方法
                response.setStatus(302);
                response.setHeader("location", request.getContextPath()+"/toLogin");
                return false;
            }
            //如果需要管理员权限但是用户的角色不是管理员时，返回权限错误信息
            if(needAdminuser && loginUser.getRole() != 1){
                throw new RuntimeException("system_permission_limit");
            }
            request.setAttribute("XXL_JOB_LOGIN_IDENTITY",loginUser);
        }
        return true;
    }
}
